package com.wpml.common.exception;

import com.wpml.common.util.ResultJson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: wp
 * @date: 2019-09-02 10:43
 **/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ResultJson requestExceptionHandler(Exception e){
        log.error("服务器出现故障", e);
        return ResultJson.builder().msg(ResultJson.ERROR_MSG).status(ResultJson.FAIL).build();
    }

    @ExceptionHandler(value = CustomException.class)
    public ResultJson requestExceptionHandler(CustomException e){
        log.error("出错了", e);
        return ResultJson.builder().msg(e.getMsg()).status(ResultJson.FAIL).build();
    }

    @ExceptionHandler(value= MethodArgumentNotValidException.class)
    public ResultJson handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{}，异常类型：{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();

        Map<String,String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError)->{
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });

        return ResultJson.builder().msg("参数格式校验失败").status(ResultJson.FAIL).data(errorMap).build();
    }
}
